#!/usr/bin/python
#coding=utf-8

import cPickle as pickle
import base64
import time
from model.dbutils import DBUtils
from utils.model import singleton

@singleton
class SessionStore(object):
    def __init__(self):
        self.dbutils = DBUtils()

    def contains(self, key):
        sql = "SELECT * FROM session WHERE sid = %s"
        rows = self.dbutils.execute(sql, (key, ))
        if rows:
            return bool(rows[0])
        else:
            return False

    def get(self, key):
        now = time.strftime("%Y-%m-%d %H:%M:%S")
        sql = "SELECT data FROM session WHERE sid = %s"
        rows = self.dbutils.execute(sql, (key, ))
        if rows:
            data = rows[0][0]
            sql = "UPDATE session SET sdate = %s WHERE sid = %s"
            self.dbutils.execute(sql, (now, key))
            return self.decode(data)
        return None

    def set(self, key, value):
        pickle_data = self.encode(value)
        if self.contains(key):
            sql = "UPDATE session SET data = %s WHERE sid = %s"
            self.dbutils.execute(sql, (pickle_data, key))
        else:
            sql = "INSERT INTO session(sid, data) VALUES (%s, %s)"
            self.dbutils.execute(sql, (key, pickle_data))

    def delete(self, key):
        sql = "DELETE FROM session WHERE sid = %s"
        self.dbutils.execute(sql, (key, ))

    def encode(self, session_dict):
        pickle_data = pickle.dumps(session_dict)
        return base64.encodestring(pickle_data)

    def decode(self, session_data):
        pickle_data = base64.decodestring(session_data)
        return pickle.loads(pickle_data)

